<?php

namespace app\api\controller;


class Hospmsg
{
    private $pagesize = 10;


    /**
     * 检查是否可以给医生发送消息
     */
    private function checkSendMsgToDoctorFlag($orderInfo)
    {

        $array = ['flag' => 0, 'msg' => ''];//flag 1不能发送消息  0可以发送消息
        if ($orderInfo['receipttime'] == 0) {
            $array['flag'] = 1;
            $array['msg'] = '医生还未接单，或者确认接单';
            return $array;
        }
        if ($orderInfo['ask_num'] <= $orderInfo['complete_num']) {
            $array['flag'] = 1;
            $array['msg'] = '咨询次数已用完';
            return $array;
        }

        $receipTime = $orderInfo['receipttime'] + $orderInfo['ask_hours'] * 3600;
        $currTime = time();
        if ($receipTime <= $currTime) {
            $array['flag'] = 1;
            $array['msg'] = '咨询时间已经超时';
            return $array;
        }
        return $array;
    }

    private function getHospWechatRelation($w)
    {
        $model = new \app\admin\model\HospWechatRelation();
        return $model->getDataForWhere($w);
    }
    /**
     * 给医生发送消息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sendToDoctor()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token,1,$_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $order_sn = trim($_REQUEST['order_sn']);
        if (empty($order_sn)) {
            $return['err'] = 10009;
            $return['msg'] = '订单号不能为空';
            echo json_encode($return, true);
            exit;
        }
        $orderModel = new \app\admin\model\HospOrder();
        $orderInfo = $orderModel->getDataForWhere(['order_sn' => $order_sn]);
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单不存在';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['uid'] != $userInfo['id']) {
            $return['err'] = 10009;
            $return['msg'] = '无权给该医生发送询诊消息';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['stat'] < 1) {
            $return['err'] = 10009;
            $return['msg'] = '订单未支付';
            echo json_encode($return, true);
            exit;
        }
        $checkFlag = $this->checkSendMsgToDoctorFlag($orderInfo);
        if ($checkFlag['flag'] == 1) {
            $return['err'] = 10009;
            $return['msg'] = $checkFlag['msg'];
            echo json_encode($return, true);
            exit;
        }

        $contents = trim($_REQUEST['contents']);
        $fj_type = trim($_REQUEST['fj_type']);
        if (empty($fj_type)) {
            if (empty($contents)) {
                $return['err'] = 10009;
                $return['msg'] = '内容不能为空';
                echo json_encode($return, true);
                exit;
            }
        }

        $fj = trim($_REQUEST['fj']);

        $data = array(
            'send_uid' => $userInfo['id'],
            'receive_uid' => $orderInfo['doctor_id'],
            'hosp_id' => $_hosp,
            'contents' => $contents,
            'fj_type' => $fj_type,
            'order_sn' => $order_sn,
            'fj' => $fj,
            'ctime' => time(),
        );

        $toolModel = new \app\admin\model\HospMsg();
        $res = $toolModel->add($data);
        if ($res) {

            $orderModel->updateForInc(['order_sn' => $orderInfo['order_sn']], "complete_num", 1);
            //给医生发送提醒消息
            $UserInfoRelatin = $this->getHospWechatRelation(["uid" => $orderInfo['doctor_id'], 'ty' => 2, 'hosp_id' => $orderInfo['hosp_id']]);
            if($UserInfoRelatin['wechat_access_token']) {
                $twMsg = "";
                if($contents)
                {
                    $twMsg=  $contents;
                }
                if($fj){
                    $twMsg=  "新的附件待查阅";
                }
                $this->addDoctorMsgWarn($UserInfoRelatin['wechat_access_token'], $orderInfo,$twMsg );
            }
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            return json($return);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }
    }


    /**
     * 给患者发送提醒通知消息
     * @param $openid
     * @param $order_info
     * @param $msg
     * @return array
     */
    public function addUserMsgWarn($openid,$order_info,$msg)
    {
        $templateID = "xbwmt1u58CR6Vrw-m3etXtYyXaeTqkKQFwzrTpwTxqM";
        $page = "/pages/index/index";
        $hosp_id = $order_info['hosp_id'];
        $client = 1;
        $miniprogram_state = "formal";
        $date=date("Y-m-d H:i:s");

        $doctorModel = new \app\admin\model\HospDoctor();
        $doctorUserInfo = $doctorModel->getDataForWhere(array('uid' => $order_info['doctor_id']));

        $templateData = '{
           "thing1": {
             "value": "' .$msg. '"
         },
         "name5": {
             "value":"' .$doctorUserInfo['name'] . '"
         },
         "time4": {
             "value": "' . $date . '"
         }
     }';
        $param=array(
            'openid'=>$openid,
            'order_sn'=>$order_info['order_sn'],
            'templateID'=>$templateID,
            'page'=>$page,
            'hosp_id'=>$hosp_id,
            'client'=>$client,
            'miniprogram_state'=>$miniprogram_state,
            'template_data'=>$templateData
        );
        $res = wechatSendSubscribeTemplateMsg($param['hosp_id'], $param['client'], $param['openid'],
            $param['templateID'], $param['page'], $param['miniprogram_state'], $param['template_data']);
        if($res['err'])
        {
            addTaskLog(array(
                'taskname' => $param['order_sn']."[患者咨询]",
                'key' => time(),
                'param' => json_encode($param,true),
                'result' => "ok",
                'ctime' => date("Y-m-d H:i:s"),
            ));
            return array('err'=>0);
        }else{
            addTaskLog(array(
                'taskname' => $param['order_sn']."[患者咨询]",
                'key' => time(),
                'param' => json_encode($param,true),
                'result' => $res['msg'],
                'ctime' => date("Y-m-d H:i:s"),
            ));
            return array('err'=>1);
        }


    }

    /**
     * 给医生发送问诊消息提醒
     * @param $order_sn
     * @param string $time
     */
    public function addDoctorMsgWarn($openid,$order_info,$msg)
    {
        $templateID = "NxAOaBmlRrHGaVTG_h-oMXbNCvwf4LraBNXMQ14pO1U";
        $page = "/pages/index/index";
        $hosp_id = $order_info['hosp_id'];
        $client = 2;
        $miniprogram_state = "formal";
        $date=date("Y-m-d H:i:s");

        $sex="女";
        if($order_info['uid_sex']==1)
        {
            $sex="男";
        }

        $templateData = '{
           "thing2": {
             "value": "' .$msg. '"
         },
         "name1": {
             "value":"' .$order_info['uid_name'] . '"
         },
         "date3": {
             "value": "' . $date . '"
         }
     }';
        $param=array(
            'openid'=>$openid,
            'order_sn'=>$order_info['order_sn'],
            'templateID'=>$templateID,
            'page'=>$page,
            'hosp_id'=>$hosp_id,
            'client'=>$client,
            'miniprogram_state'=>$miniprogram_state,
            'template_data'=>$templateData
        );

        $res = wechatSendSubscribeTemplateMsg($param['hosp_id'], $param['client'], $param['openid'],
            $param['templateID'], $param['page'], $param['miniprogram_state'], $param['template_data']);
        if($res['err'])
        {
            addTaskLog(array(
                'taskname' => $param['order_sn']."[患者咨询]",
                'key' => time(),
                'param' => json_encode($param,true),
                'result' => "ok",
                'ctime' => date("Y-m-d H:i:s"),
            ));
            return array('err'=>0);
        }else{
            addTaskLog(array(
                'taskname' => $param['order_sn']."[患者咨询]",
                'key' => time(),
                'param' => json_encode($param,true),
                'result' => $res['msg'],
                'ctime' => date("Y-m-d H:i:s"),
            ));
            return array('err'=>1);
        }


    }

    /**
     * 医生给患者发送消息
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function sendToUser()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
         $userInfo = getUserinfoForAccessToken($access_token,2,$_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $order_sn = trim($_REQUEST['order_sn']);
        if (empty($order_sn)) {
            $return['err'] = 10009;
            $return['msg'] = '订单号不能为空';
            echo json_encode($return, true);
            exit;
        }
        $orderModel = new \app\admin\model\HospOrder();
        $orderInfo = $orderModel->getDataForWhere(['order_sn' => $order_sn]);
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单不存在';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['doctor_id'] != $userInfo['id']) {
            $return['err'] = 10009;
            $return['msg'] = '无权给该用户发送消息';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['stat'] < 1) {
            $return['err'] = 10009;
            $return['msg'] = '订单未支付';
            echo json_encode($return, true);
            exit;
        }

        $fj_type = trim($_REQUEST['fj_type']);
        $contents = trim($_REQUEST['contents']);
        if (empty($fj_type)) {
            if (empty($contents)) {
                $return['err'] = 10009;
                $return['msg'] = '内容不能为空';
                echo json_encode($return, true);
                exit;
            }
        }

        $fj = trim($_REQUEST['fj']);

        $data = array(
            'send_uid' => $userInfo['id'],
            'receive_uid' => $orderInfo['uid'],
            'hosp_id' => $_hosp,
            'contents' => $contents,
            'fj_type' => $fj_type,
            'order_sn' => $order_sn,
            'fj' => $fj,
            'ctime' => time(),
        );

        $toolModel = new \app\admin\model\HospMsg();
        $res = $toolModel->add($data);
        if ($res) {

            $orderModel->updateForInc(['order_sn' => $orderInfo['order_sn']], "repeat_num", 1);
            //给用户发送提醒消息
            $UserInfoRelatin = $this->getHospWechatRelation(["uid" => $orderInfo['uid'], 'ty' => 1, 'hosp_id' => $orderInfo['hosp_id']]);
            if($UserInfoRelatin['wechat_access_token']) {
                $twMsg = "";
                if($contents)
                {
                    $twMsg=  $contents;
                }
                if($fj){
                    $twMsg=  "新的附件待查阅";
                }
                $this->addUserMsgWarn($UserInfoRelatin['wechat_access_token'], $orderInfo,$twMsg );
            }
            $return['err'] = 0;
            $return['msg'] = '操作成功';
            return json($return);
        } else {
            $return['err'] = 1;
            $return['msg'] = '操作失败';
            return json($return);
        }
    }



    public function recordFormid()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        $ty = trim($_REQUEST['ty']);
        $formid = trim($_REQUEST['formid']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        if (empty($formid)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        if (empty($ty)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        if(!in_array($ty,[1,2])){
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }

        $data = array(
            'hosp_id' => $_hosp,
            'ty' => $ty,
            'openid' => $access_token,
            'formid' => $formid,
            'num' => 0,
            'ctime' => date("Y-m-d H:i:s"),
        );
        $toolModel = new \app\admin\model\HospWechatFormid();
        $res = $toolModel->add($data);
        if ($res) {
            $return['msg'] = '成功';
            return json($return);
        } else {
            $return['err'] = 1;
            $return['msg'] = '失败';
            return json($return);
        }
    }



    /**
     * 患者获取消息列表
     * @return \think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function msgLists()
    {
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
        $userInfo = getUserinfoForAccessToken($access_token,1,$_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $order_sn = trim($_REQUEST['order_sn']);
        if (empty($order_sn)) {
            $return['err'] = 10009;
            $return['msg'] = '订单号不能为空';
            echo json_encode($return, true);
            exit;
        }
        $orderModel = new \app\admin\model\HospOrder();
        $orderInfo = $orderModel->getDataForWhere(['order_sn' => $order_sn]);
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单不存在';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['uid'] != $userInfo['id']) {
            $return['err'] = 10009;
            $return['msg'] = '您无权获取该消息';
            echo json_encode($return, true);
            exit;
        }


        $model = new \app\admin\model\HospMsg();
        $model->updateDataForWhere(['is_read' => 1], ['order_sn' => $orderInfo['order_sn'], 'receive_uid' => $userInfo['id'], 'is_read' => 0]);
        $lists = $model->lists(array('order_sn' => $orderInfo['order_sn']), $this->pagesize, '*', "id desc");
        foreach ($lists['data'] as $key => $val) {
            $lists['data'][$key]['ctimeFormat'] = date("Y-m-d H:i:s", $val['ctime']);
            $lists['data'][$key] = $this->selectFjInfo($val);
        }
        $lists['UserInfo'] = $userInfo;
        $lists['DoctorInfo'] = array();
        if ($lists['data']) {
            $DoctorInfo = getDoctorInfo($lists['data'][0]['receive_uid']);
            $lists['DoctorInfo'] = changeToDoctor($DoctorInfo, false);
        }
        $return['err'] = 0;
        $return['msg'] = '操作成功';
        $return['data'] = $lists;
        return json($return);

    }

    private function selectFjInfo($msgInfo)
    {
        $msgInfo['fj_data_list'] = array();
        if ($msgInfo['fj_type'] == 2)//、没有 1、图片 2、检测报告  3、医嘱
        {
            if ($msgInfo['fj']) {
                $msgInfo['fj_data_list'] = getNearFile($msgInfo['fj']);
            }
        } else if ($msgInfo['fj_type'] == 3) {
            if ($msgInfo['fj']) {
                $msgInfo['fj_data_list'] = getAdviceFile($msgInfo['fj']);
                $msgInfo['fj_data_list'] = changeDoctorInfoForLists($msgInfo['fj_data_list'], 'uid');
            }
        }
        return $msgInfo;
    }

    /**
     * 医生端获取消息
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function msgDoctorLists()
    {
        $access_token = trim($_REQUEST['access_token']);
        $pagesize = trim($_REQUEST['pagesize']);
        if (!empty($pagesize)) {
            $this->pagesize = $pagesize;
        }
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
         $userInfo = getUserinfoForAccessToken($access_token,2,$_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }

        $order_sn = trim($_REQUEST['order_sn']);
        if (empty($order_sn)) {
            $return['err'] = 10009;
            $return['msg'] = '订单号不能为空';
            echo json_encode($return, true);
            exit;
        }
        $orderModel = new \app\admin\model\HospOrder();
        $orderInfo = $orderModel->getDataForWhere(['order_sn' => $order_sn]);
        if (empty($orderInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '订单不存在';
            echo json_encode($return, true);
            exit;
        }

        if ($orderInfo['doctor_id'] != $userInfo['id']) {
            $return['err'] = 10009;
            $return['msg'] = '您无权获取该消息';
            echo json_encode($return, true);
            exit;
        }


        $model = new \app\admin\model\HospMsg();
        $model->updateDataForWhere(['is_read' => 1], ['order_sn' => $orderInfo['order_sn'], 'receive_uid' => $userInfo['id'], 'is_read' => 0]);
        $lists = $model->lists(array('order_sn' => $orderInfo['order_sn']), $this->pagesize, '*', "id desc");

        foreach ($lists['data'] as $key => $val) {
            $lists['data'][$key]['ctimeFormat'] = date("Y-m-d H:i:s", $val['ctime']);
            $lists['data'][$key] = $this->selectFjInfo($val);
        }
        $DoctorInfo = getDoctorInfo($userInfo['id']);
        $lists['DoctorInfo'] = changeToDoctor($DoctorInfo, false);
        $lists['UserInfo'] = array();
        if ($lists['data']) {
            $lists['UserInfo'] = getUserInfoForID($lists['data'][0]['receive_uid'], 'id,uname,nickname,weight,height,head,sex,bday,ctime,money,sleep_option,level,vip');
        }
        $return['err'] = 0;
        $return['msg'] = '操作成功';
        $return['data'] = $lists;
        return json($return);

    }


    public function latestDoctorLists()
    {
        $max = 10;//最多返回10条数据
        $access_token = trim($_REQUEST['access_token']);
        $_hosp = trim($_REQUEST['_hosp']);
        if (empty($access_token)) {
            $return['err'] = 10009;
            $return['msg'] = 'access_token不正确';
            echo json_encode($return, true);
            exit;
        }
        if (empty($_hosp)) {
            $return['err'] = 10009;
            $return['msg'] = '参数错误';
            echo json_encode($return, true);
            exit;
        }
        $hosptialInfo = getHospInfo($_hosp);
        if (empty($hosptialInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '医院信息不存在';
            echo json_encode($return, true);
            exit;
        }
        $userModel = new \app\admin\model\User();
         $userInfo = getUserinfoForAccessToken($access_token,2,$_hosp);
        if (empty($userInfo)) {
            $return['err'] = 10009;
            $return['msg'] = '未找到相关用户';
            echo json_encode($return, true);
            exit;
        }
        $model = new \app\admin\model\HospMsg();
        //1、查询最近给我发消息的记录
        $sql = "SELECT  max(id) as id,order_sn, count(*) as record_num  from (select * from t_hosp_msg where receive_uid = {$userInfo['id']}) as msg GROUP BY msg.order_sn limit {$max}";
        $allLists = $model->querySelectSQL($sql);

        $data = array();
        //分别查询
        foreach ($allLists as $key => $val) {

            $info = $model->getID($val['id']);
            if (!empty($info)) {
                $info['ctimeFormat'] = date("Y-m-d H:i:s", $info['ctime']);
                $info['distanceCtime'] = toCurrTime($info['ctime']);
                $info['UserInfo'] = getUserInfoForID($info['send_uid'], 'id,uname,nickname,weight,height,head,sex,bday,ctime,money,sleep_option,level,vip');
                $info['OrderInfo'] = getHospOrderInfo($val['order_sn'], "order_sn,stat,status");
                $info['no_read_num'] = $model->getCount(["receive_uid" => $userInfo['id'], 'order_sn' => $val['order_sn'], 'is_read' => 0]);
                $data[] = $info;
            }
        }


        $return['err'] = 0;
        $return['msg'] = '操作成功';
        $return['data'] = $data;
        return json($return);
    }

}

